<template>
  <div class="knowledge-container">
    <!-- 头部工具栏 -->
    <div class="header-toolbar">
      <div class="left-section">
        <h2>知识管理</h2>
      </div>
      <div class="right-section">
        <el-input v-model="searchQuery" placeholder="搜索知识空间 (Ctrl+K)" prefix-icon="Search" class="search-input"
          @keyup.enter="handleSearch" />
        <el-button type="primary" @click="showCreateSpaceDialog = true">
          <el-icon>
            <Plus />
          </el-icon>
          新建空间
        </el-button>
      </div>
    </div>

    <!-- 主要内容区域 -->
    <div class="main-content">
      <!-- 左侧导航 -->
      <div class="sidebar">
        <div class="nav-section">
          <h4>空间模块</h4>
          <div class="nav-item" :class="{ active: activeTab === 'all-spaces' }" @click="setActiveTab('all-spaces')">
            <el-icon>
              <Collection />
            </el-icon>
            <span>全部空间</span>
          </div>
          <div class="nav-item" :class="{ active: activeTab === 'team-spaces' }" @click="setActiveTab('team-spaces')">
            <el-icon>
              <UserFilled />
            </el-icon>
            <span>团队空间</span>
          </div>
          <div class="nav-item" :class="{ active: activeTab === 'personal-spaces' }"
            @click="setActiveTab('personal-spaces')">
            <el-icon>
              <User />
            </el-icon>
            <span>个人空间</span>
          </div>
        </div>

        <div class="nav-section">
          <h4>页面模块</h4>
          <div class="nav-item" :class="{ active: activeTab === 'recent' }" @click="setActiveTab('recent')">
            <el-icon>
              <Clock />
            </el-icon>
            <span>最近访问</span>
          </div>
          <div class="nav-item" :class="{ active: activeTab === 'favorites' }" @click="setActiveTab('favorites')">
            <el-icon>
              <Star />
            </el-icon>
            <span>我的收藏</span>
          </div>
        </div>
      </div>

      <!-- 右侧内容区域 -->
      <div class="content-area">
        <!-- 全部空间视图 -->
        <div v-if="activeTab === 'all-spaces'" class="spaces-view">
          <div class="view-header">
            <h3>全部空间</h3>
          </div>
          <div class="spaces-grid">
            <div v-for="space in filteredAllSpaces" :key="space.id" class="space-card" @click="enterSpace(space)"
              @contextmenu.prevent="showSpaceContextMenu($event, space)">
              <div class="space-header">
                <div class="space-icon" :style="{ backgroundColor: space.color || '#409EFF' }">
                  {{ space.name ? space.name.charAt(0).toUpperCase() : 'S' }}
                </div>
                <div class="space-actions">
                  <el-dropdown @command="handleSpaceAction" trigger="hover" @click.stop>
                    <el-button size="small" text class="more-options-btn">
                      <el-icon>
                        <MoreFilled />
                      </el-icon>
                    </el-button>
                    <template #dropdown>
                      <el-dropdown-menu>
                        <el-dropdown-item :command="{ action: 'edit', space }">编辑空间</el-dropdown-item>
                        <el-dropdown-item :command="{ action: 'delete', space }" divided>删除空间</el-dropdown-item>
                      </el-dropdown-menu>
                    </template>
                  </el-dropdown>
                </div>
              </div>
              <div class="space-info">
                <h4>{{ space.name }}</h4>
                <p class="space-desc">{{ space.description || '暂无描述' }}</p>
                <div class="space-stats">
                  <span class="doc-count">
                    <el-icon>
                      <Document />
                    </el-icon>
                    {{ space.documentCount || 0 }} 个文档
                  </span>
                  <span class="visibility">
                    <el-icon>
                      <Lock v-if="space.visibility === 'private'" />
                      <Unlock v-else />
                    </el-icon>
                    {{ getVisibilityDisplayText(space.visibility) }}
                  </span>
                </div>
                <div class="space-meta">
                  <el-tag :type="space.scopeType === 'team' ? 'warning' : 'info'" size="small">
                    {{ space.scopeType === 'team' ? '团队' : '个人' }}
                  </el-tag>
                  <span class="last-visit">{{ formatTime(space.updatedAt) }}</span>
                </div>
              </div>
            </div>
          </div>
          <div v-if="filteredAllSpaces.length === 0" class="empty-state">
            <el-icon size="48">
              <Collection />
            </el-icon>
            <p>暂无空间</p>
            <el-button type="primary" @click="showCreateSpaceDialog = true">创建第一个空间</el-button>
          </div>
        </div>

        <!-- 团队空间视图 -->
        <div v-if="activeTab === 'team-spaces'" class="spaces-view">
          <div class="view-header">
            <h3>团队空间</h3>
          </div>
          <div class="spaces-grid">
            <div v-for="space in teamSpaces" :key="space.id" class="space-card" @click="enterSpace(space)"
              @contextmenu.prevent="showSpaceContextMenu($event, space)">
              <div class="space-header">
                <div class="space-icon" :style="{ backgroundColor: space.color || '#409EFF' }">
                  {{ space.name ? space.name.charAt(0).toUpperCase() : 'S' }}
                </div>
                <div class="space-actions">
                  <el-dropdown @command="handleSpaceAction" trigger="hover" @click.stop>
                    <el-button size="small" text class="more-options-btn">
                      <el-icon>
                        <MoreFilled />
                      </el-icon>
                    </el-button>
                    <template #dropdown>
                      <el-dropdown-menu>
                        <el-dropdown-item :command="{ action: 'edit', space }">编辑空间</el-dropdown-item>
                        <el-dropdown-item :command="{ action: 'delete', space }" divided>删除空间</el-dropdown-item>
                      </el-dropdown-menu>
                    </template>
                  </el-dropdown>
                </div>
              </div>
              <div class="space-info">
                <h4>{{ space.name }}</h4>
                <p class="space-desc">{{ space.description || '暂无描述' }}</p>
                <div class="space-stats">
                  <span class="doc-count">
                    <el-icon>
                      <Document />
                    </el-icon>
                    {{ space.documentCount || 0 }} 个文档
                  </span>
                  <span class="visibility">
                    <el-icon>
                      <Lock v-if="space.visibility === 'private'" />
                      <Unlock v-else />
                    </el-icon>
                    {{ getVisibilityDisplayText(space.visibility) }}
                  </span>
                </div>
                <div class="space-meta">
                  <el-tag type="warning" size="small">团队</el-tag>
                  <span class="last-visit">{{ formatTime(space.updatedAt) }}</span>
                </div>
              </div>
            </div>
          </div>
          <div v-if="teamSpaces.length === 0" class="empty-state">
            <el-icon size="48">
              <UserFilled />
            </el-icon>
            <p>暂无团队空间</p>
          </div>
        </div>

        <!-- 个人空间视图 -->
        <div v-if="activeTab === 'personal-spaces'" class="spaces-view">
          <div class="view-header">
            <h3>个人空间</h3>
          </div>
          <div class="spaces-grid">
            <div v-for="space in personalSpaces" :key="space.id" class="space-card" @click="enterSpace(space)"
              @contextmenu.prevent="showSpaceContextMenu($event, space)">
              <div class="space-header">
                <div class="space-icon" :style="{ backgroundColor: space.color || '#409EFF' }">
                  {{ space.name ? space.name.charAt(0).toUpperCase() : 'S' }}
                </div>
                <div class="space-actions">
                  <el-dropdown @command="handleSpaceAction" trigger="hover" @click.stop>
                    <el-button size="small" text class="more-options-btn">
                      <el-icon>
                        <MoreFilled />
                      </el-icon>
                    </el-button>
                    <template #dropdown>
                      <el-dropdown-menu>
                        <el-dropdown-item :command="{ action: 'edit', space }">编辑空间</el-dropdown-item>
                        <el-dropdown-item :command="{ action: 'delete', space }" divided>删除空间</el-dropdown-item>
                      </el-dropdown-menu>
                    </template>
                  </el-dropdown>
                </div>
              </div>
              <div class="space-info">
                <h4>{{ space.name }}</h4>
                <p class="space-desc">{{ space.description || '暂无描述' }}</p>
                <div class="space-stats">
                  <span class="doc-count">
                    <el-icon>
                      <Document />
                    </el-icon>
                    {{ space.documentCount || 0 }} 个文档
                  </span>
                  <span class="visibility">
                    <el-icon>
                      <Lock v-if="space.visibility === 'private'" />
                      <Unlock v-else />
                    </el-icon>
                    {{ getVisibilityDisplayText(space.visibility) }}
                  </span>
                </div>
                <div class="space-meta">
                  <el-tag type="info" size="small">个人</el-tag>
                  <span class="last-visit">{{ formatTime(space.updatedAt) }}</span>
                </div>
              </div>
            </div>
          </div>
          <div v-if="personalSpaces.length === 0" class="empty-state">
            <el-icon size="48">
              <User />
            </el-icon>
            <p>暂无个人空间</p>
          </div>
        </div>

        <!-- 最近访问视图 -->
        <div v-if="activeTab === 'recent'" class="recent-view">
          <h3>最近访问</h3>
          <div class="recent-list">
            <div v-for="item in recentItems" :key="item.id" class="recent-item" @click="openDocument(item, 'recent')">
              <div class="item-icon">
                <el-icon v-if="item.type === 'space'">
                  <Collection />
                </el-icon>
                <el-icon v-else>
                  <Document />
                </el-icon>
              </div>
              <div class="item-info">
                <h4>{{ item.name }}</h4>
                <p>{{ item.spaceName || item.description }}</p>
                <span class="visit-time">{{ formatTime(item.visitTime) }}</span>
              </div>
            </div>
          </div>
          <div v-if="recentItems.length === 0" class="empty-state">
            <el-icon size="48">
              <Clock />
            </el-icon>
            <p>暂无最近访问记录</p>
          </div>
        </div>

        <!-- 收藏视图 -->
        <div v-if="activeTab === 'favorites'" class="favorites-view">
          <h3>我的收藏</h3>
          <div class="favorites-list">
            <div v-for="item in favoriteItems" :key="item.id" class="favorite-item"
              @click="openDocument(item, 'favorite')">
              <div class="item-icon">
                <el-icon v-if="item.type === 'space'">
                  <Collection />
                </el-icon>
                <el-icon v-else>
                  <Document />
                </el-icon>
              </div>
              <div class="item-info">
                <h4>{{ item.name }}</h4>
                <p>{{ item.spaceName || item.description }}</p>
              </div>
              <div class="item-actions">
                <el-button size="small" text @click.stop="removeFavorite(item.id)" title="取消收藏">
                  <el-icon>
                    <StarFilled style="color: #f56c6c;" />
                  </el-icon>
                </el-button>
              </div>
            </div>
          </div>
          <div v-if="favoriteItems.length === 0" class="empty-state">
            <el-icon size="48">
              <Star />
            </el-icon>
            <p>暂无收藏内容</p>
          </div>
        </div>
      </div>
    </div>

    <!-- 创建空间对话框 -->
    <el-dialog v-model="showCreateSpaceDialog" title="新建空间" width="500px">
      <el-form :model="newSpace" :rules="spaceRules" ref="spaceFormRef" label-width="80px">
        <el-form-item label="所属" prop="scopeType">
          <el-select v-model="newSpace.scopeType" placeholder="请选择所属">
            <el-option label="团队" value="team" />
            <el-option label="个人" value="personal" />
          </el-select>
        </el-form-item>
        <el-form-item label="空间名称" prop="name">
          <el-input v-model="newSpace.name" placeholder="请输入空间名称" />
        </el-form-item>
        <el-form-item label="可见范围" prop="visibility">
          <el-select v-model="newSpace.visibility" placeholder="请选择可见范围">
            <el-option label="公开" value="public" />
            <el-option label="私有" value="private" />
          </el-select>
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="newSpace.description" type="textarea" placeholder="请输入空间描述" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showCreateSpaceDialog = false">取消</el-button>
        <el-button type="primary" @click="createSpace">创建</el-button>
      </template>
    </el-dialog>

    <!-- 编辑空间对话框 -->
    <el-dialog v-model="showEditSpaceDialog" title="编辑空间" width="500px">
      <el-form :model="editSpace" :rules="spaceRules" ref="editSpaceFormRef" label-width="80px">
        <el-form-item label="所属" prop="scopeType">
          <el-select v-model="editSpace.scopeType" placeholder="请选择所属">
            <el-option label="团队" value="team" />
            <el-option label="个人" value="personal" />
          </el-select>
        </el-form-item>
        <el-form-item label="空间名称" prop="name">
          <el-input v-model="editSpace.name" placeholder="请输入空间名称" />
        </el-form-item>
        <el-form-item label="可见范围" prop="visibility">
          <el-select v-model="editSpace.visibility" placeholder="请选择可见范围">
            <el-option label="公开" value="public" />
            <el-option label="私有" value="private" />
          </el-select>
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="editSpace.description" type="textarea" placeholder="请输入空间描述" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showEditSpaceDialog = false">取消</el-button>
        <el-button type="primary" @click="updateSpace">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Collection, Clock, Star, Plus, Document, User, UserFilled, StarFilled, MoreFilled, Lock, Unlock
} from '@element-plus/icons-vue'
import { knowledgeSpaceApi, documentApi } from '@/api/knowledge'
import { clearExpiredCache } from '@/utils/routePreloader'

// 获取当前登录用户信息
const getCurrentUser = () => {
  try {
    const userInfo = JSON.parse(localStorage.getItem('system-user') || '{}')
    console.log('获取到的用户信息:', userInfo)
    // 优先使用name字段，如果没有则使用username字段
    const username = userInfo?.name || userInfo?.username
    console.log('提取的用户名:', username)
    if (username && username.trim() !== '') {
      return username.trim()
    }
    console.warn('用户信息不完整或为空:', userInfo)
    return null
  } catch (error) {
    console.error('获取用户信息失败:', error)
    return null
  }
}

const router = useRouter()

// 响应式数据
const searchQuery = ref('')
const spaceSearchQuery = ref('')
const activeTab = ref('all-spaces')
const showCreateSpaceDialog = ref(false)
const showEditSpaceDialog = ref(false)
const sortBy = ref('name')
const spaceFormRef = ref()
const editSpaceFormRef = ref()
const currentEditingSpace = ref(null)

const spaces = ref([])
const recentItems = ref([])
const favoriteItems = ref([])

const newSpace = reactive({
  name: '',
  scopeType: 'personal',
  visibility: 'private',
  description: ''
})

const editSpace = reactive({
  id: null,
  name: '',
  scopeType: 'personal',
  visibility: 'private',
  description: ''
})

const spaceRules = {
  name: [
    { required: true, message: '请输入空间名称', trigger: 'blur' }
  ],
  scopeType: [
    { required: true, message: '请选择所属', trigger: 'change' }
  ],
  visibility: [
    { required: true, message: '请选择可见范围', trigger: 'change' }
  ]
}

// 计算属性
const filteredAllSpaces = computed(() => {
  let filtered = spaces.value
  if (spaceSearchQuery.value) {
    filtered = filtered.filter(space =>
      space.name.toLowerCase().includes(spaceSearchQuery.value.toLowerCase()) ||
      (space.description && space.description.toLowerCase().includes(spaceSearchQuery.value.toLowerCase()))
    )
  }
  if (sortBy.value === 'name') {
    filtered.sort((a, b) => a.name.localeCompare(b.name))
  } else if (sortBy.value === 'time') {
    filtered.sort((a, b) => new Date(b.updatedAt) - new Date(a.updatedAt))
  }
  return filtered
})

const teamSpaces = computed(() => {
  return spaces.value.filter(space => space.scopeType === 'team')
})

const personalSpaces = computed(() => {
  return spaces.value.filter(space => space.scopeType === 'personal')
})

// 数据转换函数
const convertSpaceTypeToFrontend = (spaceType) => {
  const typeMap = {
    '团队': 'team',
    '个人': 'personal'
  }
  return typeMap[spaceType] || spaceType
}

const convertVisibilityToFrontend = (visibility) => {
  const visibilityMap = {
    '公开': 'public',
    '私有': 'private',
    '团队内可见': 'team',
    '仅自己可见': 'private'
  }
  return visibilityMap[visibility] || visibility
}

// 反向转换函数：前端到后端
const convertSpaceTypeToBackend = (spaceType) => {
  const typeMap = {
    'team': '团队',
    'personal': '个人'
  }
  return typeMap[spaceType] || spaceType
}

const convertVisibilityToBackend = (visibility, scopeType) => {
  if (visibility === 'public') {
    return '公开'
  } else if (visibility === 'private') {
    // 根据空间类型决定私有的具体含义
    return scopeType === 'team' ? '团队内可见' : '仅自己可见'
  }
  return visibility
}

// 获取可见性显示文本
const getVisibilityDisplayText = (visibility) => {
  const displayMap = {
    'public': '公开',
    'private': '私有',
    'team': '私有'
  }
  return displayMap[visibility] || visibility
}

// 监听器
watch(() => newSpace.scopeType, (newType) => {
  // 当空间类型改变时，重置可见性选项
  if (newType === 'team') {
    newSpace.visibility = 'public' // 团队空间默认公开
  } else if (newType === 'personal') {
    newSpace.visibility = 'private' // 个人空间默认私有
  }
})

watch(() => editSpace.scopeType, (newType) => {
  // 当编辑空间类型改变时，重置可见性选项
  if (newType === 'team') {
    editSpace.visibility = 'public' // 团队空间默认公开
  } else if (newType === 'personal') {
    editSpace.visibility = 'private' // 个人空间默认私有
  }
})

// 监听搜索框变化，实时更新搜索结果
watch(searchQuery, (newValue) => {
  if (!newValue.trim()) {
    // 当搜索框为空时，清空搜索条件
    spaceSearchQuery.value = ''
  }
})

// 方法
const setActiveTab = (tab) => {
  activeTab.value = tab
}

const enterSpace = (space) => {
  // 记录访问时间
  space.lastVisit = Date.now()
  // 跳转到空间详情页面
  router.push(`/knowledge/space/${space.id}`)
}

const openDocument = (item, source = null) => {
  if (item.type === 'space') {
    enterSpace(item)
  } else {
    // 打开文档页面，使用正确的路由路径
    const query = source ? { from: source } : {}
    router.push({
      path: `/knowledge/space/${item.spaceId}/document/${item.id}/preview`,
      query
    })
  }
}

const handleSearch = () => {
  if (searchQuery.value.trim()) {
    spaceSearchQuery.value = searchQuery.value
    setActiveTab('all-spaces')
  } else {
    // 当搜索框为空时，清空搜索条件
    spaceSearchQuery.value = ''
  }
}

const formatTime = (timestamp) => {
  if (!timestamp) return ''

  // 确保timestamp是有效的时间戳或日期字符串
  let date
  if (typeof timestamp === 'string') {
    date = new Date(timestamp)
  } else if (typeof timestamp === 'number') {
    date = new Date(timestamp)
  } else {
    return ''
  }

  // 检查日期是否有效
  if (isNaN(date.getTime())) {
    return ''
  }

  const now = new Date()
  const diff = now - date

  // 小于1分钟
  if (diff < 60 * 1000) {
    return '刚刚'
  }
  // 小于1小时
  else if (diff < 60 * 60 * 1000) {
    const minutes = Math.floor(diff / (60 * 1000))
    return `${minutes}分钟前`
  }
  // 小于1天
  else if (diff < 24 * 60 * 60 * 1000) {
    const hours = Math.floor(diff / (60 * 60 * 1000))
    return `${hours}小时前`
  }
  // 小于30天
  else if (diff < 30 * 24 * 60 * 60 * 1000) {
    const days = Math.floor(diff / (24 * 60 * 60 * 1000))
    return `${days}天前`
  }
  // 小于12个月
  else if (diff < 365 * 24 * 60 * 60 * 1000) {
    const months = Math.floor(diff / (30 * 24 * 60 * 60 * 1000))
    return `${months}个月前`
  }
  // 超过1年
  else {
    const years = Math.floor(diff / (365 * 24 * 60 * 60 * 1000))
    return `${years}年前`
  }
}

const loadSpaces = async () => {
  try {
    // 获取当前用户名
    const currentUser = getCurrentUser()
    if (!currentUser || currentUser.trim() === '') {
      ElMessage.error('无法获取当前用户信息，请重新登录')
      return
    }

    const response = await knowledgeSpaceApi.getSpaces(currentUser)
    if (response.code === '200') {
      // 转换后端数据格式以适配前端显示
      spaces.value = response.data.map(space => {
        const frontendScopeType = convertSpaceTypeToFrontend(space.spaceType)
        return {
          id: space.spaceId,
          name: space.spaceName,
          description: space.spaceDescription,
          scopeType: frontendScopeType,
          visibility: convertVisibilityToFrontend(space.visibility),
          color: getSpaceColor(frontendScopeType), // 使用转换后的类型生成颜色
          documentCount: space.documentCount || 0,
          updatedAt: new Date(space.updatedAt).getTime(),
          createdBy: { username: space.creatorUsername }
        }
      })
    } else {
      ElMessage.error(response.msg || '加载空间失败')
    }
  } catch (error) {
    console.error('加载空间失败:', error)
    ElMessage.error('加载空间失败，请稍后重试')
  }
}

// 根据空间类型生成颜色
const getSpaceColor = (spaceType) => {
  const colors = {
    'team': '#409EFF',
    'personal': '#67C23A'
  }
  return colors[spaceType] || '#409EFF'
}

const loadRecentItems = async () => {
  try {
    // 获取当前用户名
    const currentUser = getCurrentUser()
    if (!currentUser || currentUser.trim() === '') {
      console.warn('无法获取当前用户信息，跳过加载最近访问')
      return
    }

    const response = await documentApi.getRecentDocuments(currentUser)
    if (response.code === '200') {
      recentItems.value = response.data.map(item => ({
        id: item.documentId,
        name: item.documentName,
        type: 'document',
        spaceName: item.spaceName,
        spaceId: item.spaceId, // 添加spaceId字段
        visitTime: item.visitTime // 直接使用原始时间数据，让formatTime函数处理
      }))
      // 确保时间数据正确处理
      console.log('最近访问数据加载完成，共', recentItems.value.length, '条记录')
    } else {
      console.error('加载最近访问失败:', response.msg)
    }
  } catch (error) {
    console.error('加载最近访问失败:', error)
  }
}

const loadFavoriteItems = async () => {
  try {
    // 获取当前用户名
    const currentUser = getCurrentUser()
    if (!currentUser || currentUser.trim() === '') {
      console.warn('无法获取当前用户信息，跳过加载收藏文档')
      return
    }

    const response = await documentApi.getFavoriteDocuments(currentUser)
    if (response.code === '200') {
      favoriteItems.value = response.data.map(item => ({
        id: item.documentId,
        name: item.documentName,
        type: 'document',
        spaceName: item.spaceName,
        spaceId: item.spaceId // 添加spaceId字段以支持文档预览跳转
      }))
    } else {
      console.error('加载收藏失败:', response.msg)
    }
  } catch (error) {
    console.error('加载收藏失败:', error)
  }
}

const addFavorite = async (documentId) => {
  try {
    // 获取当前用户名
    const currentUser = getCurrentUser()
    if (!currentUser || currentUser.trim() === '') {
      ElMessage.error('无法获取当前用户信息，请重新登录')
      return
    }

    const response = await documentApi.addToFavorites(documentId, currentUser)
    if (response.code === '200') {
      ElMessage.success('已添加到收藏')
      // 重新加载收藏列表
      await loadFavoriteItems()
    } else {
      ElMessage.error(response.msg || '收藏失败')
    }
  } catch (error) {
    console.error('添加收藏失败:', error)
    ElMessage.error('添加收藏失败，请稍后重试')
  }
}

const removeFavorite = async (itemId) => {
  try {
    // 获取当前用户名
    const currentUser = getCurrentUser()
    if (!currentUser || currentUser.trim() === '') {
      ElMessage.error('无法获取当前用户信息，请重新登录')
      return
    }

    const response = await documentApi.removeFromFavorites(itemId, currentUser)
    if (response.code === '200') {
      favoriteItems.value = favoriteItems.value.filter(item => item.id !== itemId)
      ElMessage.success('已取消收藏')
    } else {
      ElMessage.error(response.msg || '取消收藏失败')
    }
  } catch (error) {
    console.error('取消收藏失败:', error)
    ElMessage.error('取消收藏失败，请稍后重试')
  }
}

const createSpace = async () => {
  if (!spaceFormRef.value) return

  try {
    await spaceFormRef.value.validate()

    // 获取当前用户名
    const currentUser = getCurrentUser()
    if (!currentUser || currentUser.trim() === '') {
      ElMessage.error('无法获取当前用户信息，请重新登录')
      return
    }

    // 调用后端API创建空间
    const spaceData = {
      spaceName: newSpace.name,
      spaceType: convertSpaceTypeToBackend(newSpace.scopeType),
      visibility: convertVisibilityToBackend(newSpace.visibility, newSpace.scopeType),
      spaceDescription: newSpace.description
    }

    console.log('准备发送的空间数据:', spaceData)
    console.log('准备发送的用户名:', currentUser)
    const response = await knowledgeSpaceApi.createSpace(spaceData, currentUser)
    console.log('后端响应:', response)
    if (response.code === '200') {
      ElMessage.success('创建成功')
      showCreateSpaceDialog.value = false

      // 清理相关缓存，确保获取最新数据
      clearExpiredCache()

      // 重新加载空间列表
      await loadSpaces()

      // 重置表单
      Object.assign(newSpace, {
        name: '',
        scopeType: 'personal',
        visibility: 'private',
        description: ''
      })
    } else {
      ElMessage.error(response.msg || '创建失败')
    }
  } catch (error) {
    console.error('创建空间失败:', error)
    ElMessage.error('创建空间失败，请稍后重试')
  }
}

const handleSpaceAction = (command) => {
  const { action, space } = command
  if (action === 'edit') {
    editSpaceAction(space)
  } else if (action === 'delete') {
    deleteSpaceAction(space)
  }
}

const showSpaceContextMenu = (event, space) => {
  // 右键菜单功能可以在这里实现
  console.log('右键菜单', space)
}

const editSpaceAction = (space) => {
  currentEditingSpace.value = space
  Object.assign(editSpace, {
    id: space.id,
    name: space.name,
    scopeType: space.scopeType,
    visibility: space.visibility,
    description: space.description || ''
  })
  showEditSpaceDialog.value = true
}

const deleteSpaceAction = async (space) => {
  try {
    // 获取当前用户名
    const currentUser = getCurrentUser()
    if (!currentUser || currentUser.trim() === '') {
      ElMessage.error('无法获取当前用户信息，请重新登录')
      return
    }

    await ElMessageBox.confirm(
      `确定要删除空间 "${space.name}" 吗？删除后将无法恢复。`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )

    // 调用后端API删除空间
    const response = await knowledgeSpaceApi.deleteSpace(space.id, currentUser)
    if (response.code === '200') {
      // 清理相关缓存，确保获取最新数据
      clearExpiredCache()

      const index = spaces.value.findIndex(s => s.id === space.id)
      if (index > -1) {
        spaces.value.splice(index, 1)
        ElMessage.success('删除成功')
      }
    } else {
      ElMessage.error(response.msg || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除空间失败:', error)
      ElMessage.error('删除空间失败，请稍后重试')
    }
  }
}

const updateSpace = async () => {
  if (!editSpaceFormRef.value) return

  try {
    await editSpaceFormRef.value.validate()

    // 获取当前用户名
    const currentUser = getCurrentUser()
    if (!currentUser || currentUser.trim() === '') {
      ElMessage.error('无法获取当前用户信息，请重新登录')
      return
    }

    // 调用后端API更新空间
    const spaceData = {
      spaceName: editSpace.name,
      spaceType: convertSpaceTypeToBackend(editSpace.scopeType),
      visibility: convertVisibilityToBackend(editSpace.visibility, editSpace.scopeType),
      spaceDescription: editSpace.description,
      isDeleted: false
      // 注意：不更新creatorUsername，创建者信息不应该被修改
    }

    const response = await knowledgeSpaceApi.updateSpace(editSpace.id, spaceData, currentUser)
    if (response.code === '200') {
      ElMessage.success('更新成功')
      showEditSpaceDialog.value = false
      currentEditingSpace.value = null

      // 清理相关缓存，确保获取最新数据
      clearExpiredCache()

      // 重新加载空间列表
      await loadSpaces()

      // 重置表单
      Object.assign(editSpace, {
        id: null,
        name: '',
        scopeType: 'personal',
        visibility: 'private',
        description: ''
      })
    } else {
      ElMessage.error(response.msg || '更新失败')
    }
  } catch (error) {
    console.error('更新空间失败:', error)
    ElMessage.error('更新空间失败，请稍后重试')
  }
}

// 生命周期
onMounted(() => {
  loadSpaces()
  loadRecentItems()
  loadFavoriteItems()
})
</script>

<style scoped>
.knowledge-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f5f5f5;
}

.header-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 24px;
  background: white;
  border-bottom: 1px solid #e8e8e8;
}

.left-section h2 {
  margin: 0;
  color: #333;
}

.right-section {
  display: flex;
  align-items: center;
  gap: 12px;
}

.search-input {
  width: 300px;
}

.main-content {
  display: flex;
  flex: 1;
  overflow: hidden;
}

.sidebar {
  width: 240px;
  background: white;
  border-right: 1px solid #e8e8e8;
  padding: 16px 0;
  overflow-y: auto;
}

.nav-section {
  margin-bottom: 24px;
}

.nav-section h4 {
  margin: 0 0 12px 16px;
  color: #999;
  font-size: 12px;
  font-weight: normal;
  text-transform: uppercase;
}

.nav-item {
  display: flex;
  align-items: center;
  padding: 12px 16px;
  cursor: pointer;
  transition: all 0.2s;
  color: #666;
}

.nav-item:hover {
  background-color: #f5f5f5;
  color: #333;
}

.nav-item.active {
  background-color: #e6f7ff;
  color: #1890ff;
  border-right: 3px solid #1890ff;
}

.nav-item .el-icon {
  margin-right: 8px;
  font-size: 16px;
}

.content-area {
  flex: 1;
  padding: 24px;
  overflow-y: auto;
}

.view-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.view-header h3 {
  margin: 0;
  color: #333;
}

.view-controls {
  display: flex;
  align-items: center;
}

.spaces-view {
  background: white;
  padding: 24px;
  border-radius: 8px;
}

.spaces-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 16px;
}

.space-card {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 16px;
  cursor: pointer;
  transition: all 0.2s;
  border: 1px solid #e8e8e8;
}

.space-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  transform: translateY(-2px);
}

.space-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 12px;
}

.space-icon {
  width: 40px;
  height: 40px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-weight: bold;
  font-size: 18px;
}

.space-actions {
  opacity: 0;
  transition: opacity 0.2s;
}

.space-card:hover .space-actions {
  opacity: 1;
}

.more-options-btn {
  border: 1px solid transparent;
  border-radius: 4px;
  padding: 4px;
  transition: all 0.2s;
}

.more-options-btn:hover {
  border-color: #409EFF;
  background-color: #f0f9ff;
}

.space-card:hover .more-options-btn {
  border-color: #d1d5db;
}

.space-stats {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
  font-size: 12px;
  color: #666;
}

.doc-count,
.visibility {
  display: flex;
  align-items: center;
  gap: 4px;
}

.doc-count .el-icon,
.visibility .el-icon {
  font-size: 14px;
}

.space-info h4 {
  margin: 0 0 8px 0;
  color: #333;
  font-size: 16px;
}

.space-desc {
  color: #666;
  font-size: 14px;
  margin: 0 0 12px 0;
  line-height: 1.4;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.space-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 12px;
}

.last-visit {
  color: #999;
}

.empty-state {
  text-align: center;
  padding: 40px;
  color: #999;
}

.empty-state .el-icon {
  margin-bottom: 16px;
}

.empty-state p {
  margin: 0 0 16px 0;
}

.recent-view,
.favorites-view {
  background: white;
  padding: 24px;
  border-radius: 8px;
}

.recent-view h3,
.favorites-view h3 {
  margin: 0 0 20px 0;
  color: #333;
}

.recent-list,
.favorites-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.recent-item,
.favorite-item {
  display: flex;
  align-items: center;
  padding: 12px;
  background: #f8f9fa;
  border-radius: 6px;
  transition: background-color 0.2s;
  cursor: pointer;
}

.recent-item:hover,
.favorite-item:hover {
  background: #e9ecef;
}

.item-icon {
  margin-right: 12px;
  color: #666;
  font-size: 20px;
}

.item-info {
  flex: 1;
}

.item-info h4 {
  margin: 0 0 4px 0;
  color: #333;
  font-size: 14px;
}

.item-info p {
  margin: 0;
  color: #666;
  font-size: 12px;
}

.visit-time {
  font-size: 11px;
  color: #999;
  background: #f0f0f0;
  padding: 2px 6px;
  border-radius: 10px;
  display: inline-block;
  margin-top: 4px;
}

.item-actions {
  margin-left: 12px;
}
</style>